﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Simple.Service;
using Simple.Common.EasyUICommon;
using System.Reflection;
using Simple.Entity;
using Simple.Web.Framework.Infrastructure.Aop;
using Simple.Web.Framework.Infrastructure;
using Simple.ViewModel;
using Simple.Entity.Models;
using Simple.EF;
using EntityFramework.Extensions;
using Simple.Entity.Enums;
using Simple.Web.Framework;
using Simple.Common.Core.Encryption;
using Simple.Common.Infrastructure;
using Simple.Common.Core.Tools;

namespace HBootStrap.Admin.Controllers
{
    public class SetUpController : Controller
    {
        private const string _defaultIcon = "fa fa-file-o";
        private const string _modularValue = "#";
        private const string _roleName = "系统管理员";
        private const string _createUser = "系统自建";
        private DateTime _createTime = DateTime.Now;
        private List<Sys_Menu> _sys_MenuList = new List<Sys_Menu>();

        private readonly WorkEfDbContext ef;

        public SetUpController(WorkEfDbContext workEfDbContext)
        {
            ef = workEfDbContext;
        }

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(SetUpDto model)
        {
            _sys_MenuList.Clear();
            var ret = RefreshMenus();
            if (ret.statusCode != SimpleResultCode.Success)
                return Json(ret, JsonRequestBehavior.AllowGet);

            Sys_Role role = new Sys_Role
            {
                CreateTime = _createTime,
                CreateUser = _createUser,
                RoleName = _roleName,
                ModifyTime = _createTime,
                ModifyUser = _createUser
            };
            ef.Sys_Role.Add(role);
            ef.SaveChanges();

            Sys_User user = ef.Sys_User.FirstOrDefault(m => m.LoginNo == model.LoginName);
            if (user == null)
            {
                string salt = RandomHelper.GetRandom().ToString();
                user = new Sys_User()
                {
                    LoginNo = model.LoginName,
                    PassWord = SimpleMD5Helper.GetMD5(model.PassWord + salt),
                    PassWordSalt = salt,
                    RoleId = role.Id,
                    CreateTime = _createTime,
                    CreateUser = _createUser,
                    IsActive = true,
                    IsDeleted = false
                };
                ef.Sys_User.Add(user);
            }
            else
            {
                user.PassWord = SimpleMD5Helper.GetMD5(model.PassWord + user.PassWordSalt);
                user.RoleId = role.Id;
                user.IsActive = true;
                user.IsDeleted = false;
                user.CreateTime = _createTime;
                user.CreateUser = _createUser;
               // return Json(SimpleResult.GetError("该用户名已经存在"), JsonRequestBehavior.AllowGet);
            }
            ef.SaveChanges();

            var menuIdList = _sys_MenuList.Select(m => m.Id).ToList();
            List<Sys_UserForMenu> sys_UserForMenuList = new List<Sys_UserForMenu>();

            if (menuIdList != null && menuIdList.Count > 0)
            {
                foreach (var item in menuIdList)
                {
                    sys_UserForMenuList.Add(new Sys_UserForMenu()
                    {
                        CreateTime = _createTime,
                        CreateUser = _createUser,
                        MenuId = item,
                        UserId = user.Id
                    });
                }
                ef.Sys_UserForMenu.Where(m => m.UserId == user.Id).Delete();
                ef.Sys_UserForMenu.AddRange(sys_UserForMenuList);
                ef.SaveChanges();
            }

            ret.redirectUrl = Url.Action("Login", "Login");
            return Json(ret, JsonRequestBehavior.AllowGet);
        }

        private SimpleResult RefreshMenus()
        {
            int delcount = ef.Sys_Menu.Delete();

            var types = Assembly.GetExecutingAssembly().GetTypes();

            List<Sys_Menu> menuList = new List<Sys_Menu>();
            List<Sys_Menu> actionMenuList = new List<Sys_Menu>();
            List<Sys_Menu> modularMenuList = new List<Sys_Menu>();

            foreach (var type in types)
            {
                if (type.BaseType.Name == "BaseController")//如果是Controller
                {
                    var members = type.GetMethods();
                    foreach (var member in members)
                    {
                        if (member.ReturnType.Name == "ActionResult")//如果是Action
                        {
                            object[] menuAttrs = member.GetCustomAttributes(typeof(MenuViewFilterAttribute), false);

                            if (menuAttrs.Length > 0)
                            {
                                var attribute = menuAttrs[0] as MenuViewFilterAttribute;
                                string menuName = attribute.MenuName;
                                string modularName = attribute.ModularName;
                                int sort = attribute.Sort;

                                Sys_Menu modularMenu = modularMenuList.FirstOrDefault(m => m.MenuName == modularName);
                                if (modularMenu == null)
                                {
                                    modularMenu = new Sys_Menu()
                                    {
                                        ActionName = _modularValue,
                                        ControllerName = _modularValue,
                                        MenuName = modularName,
                                        Icon = _defaultIcon,
                                        Sort = 0,
                                        ParentId = 0,
                                        MenuType = MenuTypeEnum.菜单模块,
                                        ActionType = ActionTypeEnum.None
                                    };
                                    ef.Sys_Menu.Add(modularMenu); //新增顶级菜单
                                    ef.SaveChanges();
                                    modularMenuList.Add(modularMenu);
                                }

                                var menu = new Sys_Menu()
                                {
                                    ActionName = member.Name,
                                    ControllerName = GetControllerName(type.Name),
                                    Icon = _defaultIcon,
                                    MenuName = menuName,
                                    Sort = sort,
                                    ParentId = modularMenu.Id,
                                    MenuType = MenuTypeEnum.普通菜单,
                                    ActionType = ActionTypeEnum.None
                                };
                                menuList.Add(menu);
                            }
                        }
                    }
                }
            }

            ef.Sys_Menu.AddRange(menuList); //新增左边侧边栏菜单
            ef.SaveChanges();

            foreach (var type in types)
            {
                if (type.BaseType.Name == "BaseController")//如果是Controller
                {
                    var members = type.GetMethods();
                    foreach (var member in members)
                    {
                        if (member.ReturnType.Name == "ActionResult")//如果是Action
                        {
                            object[] actionMenuAttrs = member.GetCustomAttributes(typeof(ActionViewFilterAttribute), true);
                            if (actionMenuAttrs.Length > 0)
                            {
                                var attribute = actionMenuAttrs[0] as ActionViewFilterAttribute;
                                string menuName = attribute.MenuName;
                                string actionName = attribute.ActionName;
                                ActionTypeEnum actionType = attribute.ActionType;
                                int sort = attribute.Sort;

                                long parentId = menuList.Find(m => m.MenuName == menuName).Id;
                                Sys_Menu actionMenu = actionMenuList.FirstOrDefault(m => m.MenuName == actionName && m.ParentId == parentId);
                                if (actionMenu == null)
                                {
                                    var menu = new Sys_Menu()
                                    {
                                        ActionName = member.Name,
                                        ControllerName = GetControllerName(type.Name),
                                        Icon = ActionTypeHelper.GetDefaultIcon(actionType) ?? _defaultIcon,
                                        MenuName = actionName,
                                        Sort = sort,
                                        ParentId = parentId,
                                        MenuType = MenuTypeEnum.菜单按钮,
                                        ActionType = actionType
                                    };
                                    actionMenuList.Add(menu);
                                }
                            }
                        }
                    }
                }
            }

            ef.Sys_Menu.AddRange(actionMenuList); //新增左边侧边栏菜单
            var ret = ef.SaveChanges();
            _sys_MenuList.AddRange(modularMenuList);
            _sys_MenuList.AddRange(menuList);
            _sys_MenuList.AddRange(actionMenuList);
            if (ret > 0)
            {
                return SimpleResult.GetRight();
            }
            return SimpleResult.GetError();
        }

        private string GetControllerName(string name)
        {
            return name.Substring(0, name.Length - 10);
        }
    }
}
